/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.put.dcs_modeler.wizards.newCFMProject;
import org.netbeans.api.java.project.JavaProjectConstants;

import java.awt.Component;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.swing.JComponent;
import javax.swing.event.ChangeListener;
import org.netbeans.api.java.classpath.ClassPath;
import org.netbeans.api.java.project.classpath.ProjectClassPathModifier;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ProjectManager;
import org.netbeans.api.project.ProjectUtils;
import org.netbeans.api.project.SourceGroup;
import org.netbeans.api.project.Sources;
import org.netbeans.spi.project.AuxiliaryConfiguration;
import org.netbeans.spi.project.ui.support.ProjectChooser;
import org.netbeans.spi.project.ui.templates.support.Templates;
import org.openide.WizardDescriptor;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.filesystems.Repository;
import org.openide.loaders.DataFolder;
import org.openide.loaders.DataObject;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.openide.xml.XMLUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import pl.put.dcs_modeler.config.ConfigSingleton;
import pl.put.dcs_modeler.project.projectPropertiesExtensions.dcsProjectProperties.projectConfigModel.DCSServerConfig;
import pl.put.dcs_modeler.utils.DCSProjectUtil;

public class CFMWizardIterator implements WizardDescriptor./*Progress*/InstantiatingIterator
{

    private static Logger log =
            Logger.getLogger( CFMWizardIterator.class.getName() );
    private int index;
    private WizardDescriptor.Panel[] panels;
    private WizardDescriptor wiz;

    public CFMWizardIterator()
    {
    }

    public static CFMWizardIterator createIterator()
    {
        return new CFMWizardIterator();
    }

    private WizardDescriptor.Panel[] createPanels()
    {
        return new WizardDescriptor.Panel[]
                {
                    new CFMWizardPanel(),
                };
    }

    private String[] createSteps()
    {
        return new String[]
                {
                    NbBundle.getMessage( CFMWizardIterator.class, "LBL_CreateProjectStep" )
                };
    }

    @Override
    public Set/*<FileObject>*/ instantiate(/*ProgressHandle handle*/) throws IOException
    {
        ConfigSingleton cs = ConfigSingleton.getInstance();
        cs.setDataModelPath( ( String )wiz.getProperty( "dmJarPath" ) );
        Set<FileObject> resultSet = new LinkedHashSet<FileObject>();
        File dirF = FileUtil.normalizeFile( ( File )wiz.getProperty( "projdir" ) );
        dirF.mkdirs();

        FileObject template = Templates.getTemplate( wiz );
        FileObject dir = FileUtil.toFileObject( dirF );
        unZipFile( template.getInputStream(), dir );

        FileObject projectRsrc = Repository.getDefault().getDefaultFileSystem().findResource( "Templates/Project/DCS/DCS Project" );
        String defaultProjectPkg = ( String )projectRsrc.getAttribute( "defaultProjectSrcPackage" );
        //ProjectInformation projectInfo = ProjectUtils.getInformation( project );

        // pozyskanie ptrzebnych danych
        String projectName = ( String )wiz.getProperty( "name" );
        FileObject temp = Repository.getDefault().getDefaultFileSystem().findResource( "Templates/DCS/DCSComputingModel.dcsmodel" );
        String pathToModel = "src/" + defaultProjectPkg + "/" + projectName + "/" + ( String )temp.getAttribute( "defaultPackage" ) ;

        // pozyskanie ptrzebnych danych
        FileObject tempCOs = Repository.getDefault().getDefaultFileSystem().findResource( "Templates/DCS/newComputingObject" );
        String pathToCO = "src/" + defaultProjectPkg + "/" + projectName + "/" + ( String )tempCOs.getAttribute( "defaultPackage" ) ;
        FileUtil.createFolder( dir, pathToCO );
        //FileObject temp = Repository.getDefault().getDefaultFileSystem().findResource( "Templates/DCS/DCSComputingModel.dcsmodel" );
        //temp = template.getParent().getFileObject( "DataAgregator", "java" );
        DataObject dTemp = DataObject.find( temp );
        DataFolder pathCM = DataFolder.create( DataFolder.findFolder( dir ), pathToModel );
        try
        {
            dTemp.createFromTemplate( pathCM );
            //FileObject fo = FileUtil.createData( new File( pathCM.getPrimaryFile().getPath() + File.separator + temp.getNameExt() ) );
            //resultSet.add( fo ); // oznacza to, ze ma zostac otworzony ten plik po stworzeniu pjektu. Dlaczego sie wysypuje?
        }
        catch ( IOException iOException )
        {
            iOException.printStackTrace();
        }

        // Always open top dir as a project:
        resultSet.add( dir );

        // Look for nested projects to open as well:
        Enumeration<? extends FileObject> e = dir.getFolders( true );
        while ( e.hasMoreElements() )
        {
            FileObject subfolder = e.nextElement();
            if ( ProjectManager.getDefault().isProject( subfolder ) )
            {
                resultSet.add( subfolder );
            }
        }

        File parent = dirF.getParentFile();
        if ( parent != null && parent.exists() )
        {
            ProjectChooser.setProjectsFolder( parent );
        }
        //log.info( "dssssssss------------------------------------" );
        Project project = ProjectManager.getDefault().findProject( dir );
        setProjectConfiguration( project );
        addLibsToProject( project );
        return resultSet;
    }

    /**
     * Convenience method to obtain the source root folder.
     * @param project the Project object
     * @return the FileObject of the source root folder
     */
    public static FileObject getSourceRoot( Project project )
    {
        if ( project == null )
        {
            return null;
        }

        // Search the ${src.dir} Source Package Folder first, use the first source group if failed.
        Sources src = ProjectUtils.getSources( project );
        SourceGroup[] grp = src.getSourceGroups( JavaProjectConstants.SOURCES_TYPE_JAVA );
        for ( int i = 0; i < grp.length; i++ )
        {
            if ( "${src.dir}".equals( grp[i].getName() ) )
            { // NOI18N
                return grp[i].getRootFolder();
            }
        }
        if ( grp.length != 0 )
        {
            return grp[0].getRootFolder();
        }

        return null;
    }

    private void addLibsToProject( Project proj ) throws IOException
    {
        //log.info(  "path: file://" + ( String )wiz.getProperty( "dmJarPath" ) );
        FileObject jar = FileUtil.createData( new File( ( String )wiz.getProperty( "dmJarPath" ) ) );
        FileObject jarRoot = FileUtil.getArchiveRoot( jar );
        FileObject src = proj.getProjectDirectory().getFileObject( "src" );
         
        ProjectClassPathModifier.addRoots( new URL[]{ jarRoot.getURL() }, src, ClassPath.COMPILE );
    }

    private void setProjectConfiguration( Project proj ) throws IOException
    {

        try
        {
            Document doc = XMLUtil.createDocument( "root", null, null, null );
            Element fragment = doc.createElementNS( "dcsProjectConfiguration", "dcsProjectConfiguration" );
            Element dataModel = doc.createElement( "dataModel" );
            dataModel.setAttribute( "path", ( String )wiz.getProperty( "dmJarPath" ) );
            fragment.appendChild( dataModel );

            // ustwienie flagi
            Element isDCS = doc.createElement( "isDCSProject" );
            isDCS.setAttribute( "val", "true" );
            fragment.appendChild( isDCS );

            //serverPath
            //AuxiliaryConfiguration ac = ( AuxiliaryConfiguration )project.getLookup().lookupResult( AuxiliaryConfiguration.class );
            AuxiliaryConfiguration ac = ProjectUtils.getAuxiliaryConfiguration( proj );
            ac.putConfigurationFragment( fragment, false );

            // wydajniejsze jest rozbudowanie powyzszego sposobu tworzenia dokumentu, ale tracimy wtedy elastycznoc.
            // Ciezko pozniej bedzie sprawowac kontrole na formatem tworzonego dokumentu (bo roznych mijescach bedzie trzeba to zmeiniac, a nie w jednym)
            List< DCSServerConfig > servers = new ArrayList< DCSServerConfig >();
            DCSServerConfig svrCfg = new DCSServerConfig();
            svrCfg.setServerPath( ( String )wiz.getProperty( "serverPath" ) );
            servers.add( svrCfg );
            DCSProjectUtil.setServersConfig( proj, servers );
        }
        catch ( Exception exp )
        {
            System.out.println( exp.getMessage() );
        }

    }

    @Override
    public void initialize( WizardDescriptor wiz )
    {
        this.wiz = wiz;
        index = 0;
        panels = createPanels();
        // Make sure list of steps is accurate.
        String[] steps = createSteps();
        for ( int i = 0; i < panels.length; i++ )
        {
            Component c = panels[i].getComponent();
            if ( steps[i] == null )
            {
                // Default step name to component name of panel.
                // Mainly useful for getting the name of the target
                // chooser to appear in the list of steps.
                steps[i] = c.getName();
            }
            if ( c instanceof JComponent )
            { // assume Swing components
                JComponent jc = ( JComponent )c;
                // Step #.
                jc.putClientProperty( "WizardPanel_contentSelectedIndex", new Integer( i ) );
                // Step name (actually the whole list for reference).
                jc.putClientProperty( "WizardPanel_contentData", steps );
            }
        }
    }

    public void uninitialize( WizardDescriptor wiz )
    {
        this.wiz.putProperty( "projdir", null );
        this.wiz.putProperty( "name", null );
        this.wiz = null;
        panels = null;
    }

    public String name()
    {
        return MessageFormat.format( "{0} of {1}",
                new Object[]
                {
                    new Integer( index + 1 ), new Integer( panels.length )
                } );
    }

    public boolean hasNext()
    {
        return index < panels.length - 1;
    }

    public boolean hasPrevious()
    {
        return index > 0;
    }

    public void nextPanel()
    {
        if ( !hasNext() )
        {
            throw new NoSuchElementException();
        }
        index++;
    }

    public void previousPanel()
    {
        if ( !hasPrevious() )
        {
            throw new NoSuchElementException();
        }
        index--;
    }

    public WizardDescriptor.Panel current()
    {
        return panels[index];
    }

    // If nothing unusual changes in the middle of the wizard, simply:
    public final void addChangeListener( ChangeListener l )
    {
    }

    public final void removeChangeListener( ChangeListener l )
    {
    }

    private static void unZipFile( InputStream source, FileObject projectRoot ) throws IOException
    {
        try
        {
            ZipInputStream str = new ZipInputStream( source );
            ZipEntry entry;
            while ( ( entry = str.getNextEntry() ) != null )
            {
                if ( entry.isDirectory() )
                {
                    FileUtil.createFolder( projectRoot, entry.getName() );
                }
                else
                {
                    FileObject fo = FileUtil.createData( projectRoot, entry.getName() );
                    if ( "nbproject/project.xml".equals( entry.getName() ) )
                    {
                        // Special handling for setting name of Ant-based projects; customize as needed:
                        filterProjectXML( fo, str, projectRoot.getName() );
                    }
                    else
                    {
                        writeFile( str, fo );
                    }
                }
            }
        } finally
        {
            source.close();
        }
    }

    private static void writeFile( ZipInputStream str, FileObject fo ) throws IOException
    {
        OutputStream out = fo.getOutputStream();
        try
        {
            FileUtil.copy( str, out );
        } finally
        {
            out.close();
        }
    }

    private static void filterProjectXML( FileObject fo, ZipInputStream str, String name ) throws IOException
    {
        ConfigSingleton cs = ConfigSingleton.getInstance();
        try
        {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            FileUtil.copy( str, baos );
            Document doc = XMLUtil.parse( new InputSource( new ByteArrayInputStream( baos.toByteArray() ) ), false, false, null, null );
            NodeList nl = doc.getDocumentElement().getElementsByTagName( "data" );
            if ( nl != null )
            {
                for ( int i = 0; i < nl.getLength(); i++ )
                {
                    Element el = ( Element )nl.item( i );
                    log.info( el.getTagName() );
                    Node parent = el.getParentNode();
                    if ( parent != null && "configuration".equals( parent.getNodeName() ) )
                    {
                        NodeList atts = el.getChildNodes();
                        for ( int iterator = 0; iterator < atts.getLength(); iterator++ )
                        {
                            Node att = atts.item( iterator );
                            log.info( "ppppp" + att.getNodeName() );
                            if ( att.getNodeName().equals( "name" ) )
                            {
                                NodeList nl2 = att.getChildNodes();
                                if ( nl2.getLength() > 0 )
                                {
                                    nl2.item( 0 ).setNodeValue( name );
                                    log.info( nl2.item( 0 ).getNodeName() );
                                }
                            }
                        /*else if ( att.getNodeName().equals( "dataModelPath" ) )
                        {
                        NodeList nl2 = att.getChildNodes();
                        if ( nl2.getLength() > 0 )
                        {
                        //ConfigSingleton cs = ConfigSingleton.getInstance();
                        nl2.item( 0 ).setNodeValue( cs.getDataModelPath() );
                        }
                        }*/
                        }

                        break;
                    }
                }

            }
            // zapis sciezki do modelu danych


            OutputStream out = fo.getOutputStream();
            try
            {
                XMLUtil.write( doc, out, "UTF-8" );
            } finally
            {
                out.close();
            }
        }
        catch ( Exception ex )
        {
            Exceptions.printStackTrace( ex );
            writeFile( str, fo );
        }

    }
}
